package cn.haoran.common.exception;

import cn.haoran.common.utils.ResultInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Create by hanran on 2019/6/15
 */
@RestControllerAdvice
public class AppExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(AppException.class)
    public ResultInfo handleAppException(AppException e){
        ResultInfo r = new ResultInfo();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        logger.error("<全局异常> - [用户自定义异常] code:{}, msg:{}", e.getCode(), e.getMsg(), e);
        return r;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultInfo handlerNoFoundException(Exception e) {
        // logger.error(e.getMessage(), e);
        logger.error("<全局异常> - [用户自定义异常] code:{}, msg:{}", 404, "路径不存在，请检查路径是否正确", e);
        return ResultInfo.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResultInfo handleDuplicateKeyException(DuplicateKeyException e){
        //logger.error(e.getMessage(), e);
        logger.error("<全局异常> - [用户自定义异常] code:{}, msg:{}", 1001, "数据库中已存在该记录", e);
        return ResultInfo.error("数据库中已存在该记录");
    }

    @ExceptionHandler(AuthorizationException.class)
    public ResultInfo handleAuthorizationException(AuthorizationException e){
        //logger.error(e.getMessage(), e);
        logger.error("<全局异常> - [用户自定义异常] code:{}, msg:{}", 403, "没有权限，请联系管理员授权", e);
        return ResultInfo.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Exception.class)
    public ResultInfo handleException(Exception e){
        logger.error(e.getMessage(), e);
        return ResultInfo.error();
    }
}
